package org.example.security;

import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.example.common.annotation.RequirePermission;
import org.example.common.result.Result;
import org.example.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class PermissionAspect {

    @Autowired
    private PermissionService permissionService;

    @Autowired
    private HttpServletRequest request;

    @Around("@annotation(requirePermission)")
    public Object checkPermission(ProceedingJoinPoint pjp, RequirePermission requirePermission) throws Throwable {
        Object userIdObj = request.getAttribute("userId");
        if (userIdObj == null) {
            return Result.unauthorized("未授权");
        }
        Long userId = (Long) userIdObj;

        String[] codes = requirePermission.value();
        boolean requireAll = requirePermission.requireAll();

        boolean pass;
        if (requireAll) {
            pass = permissionService.hasAllPermissions(userId, java.util.Arrays.asList(codes));
        } else {
            pass = permissionService.hasAnyPermission(userId, java.util.Arrays.asList(codes));
        }

        if (!pass) {
            return Result.forbidden("无权限");
        }
        return pjp.proceed();
    }
}



































